import React, { useEffect, useState } from 'react'

import { loadSunData } from '@/apis/sun'
import { useNavigate, useParams } from 'react-router-dom'
import {
  AnalysisResult,
  BattleValue,
  BattleValueExt2,
  NameValueLength
} from '@/types/sun'
import { Toaster } from '@/components/ui/toaster'
import Top30Table from '@/components/sun2/Top30Table'
import SortableTable from '@/components/sun2/SortableTable'
// 不要 import echarts，不要 import Pie/SmoothData 里用到的 echarts
import Pie from '@/components/sun2/Pie'
import SmoothData from '@/components/sun2/smoothData'
import DynamicDots from '@/components/DynamicDots'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from '@/components/ui/card'
import { battleRecordsStore } from '@/store/battle'
import AnalysisComponent from './analysis'
import SummaryStats from './SummaryStats'
import Radar from '@/components/sun2/Radar'

// 页面详情
export default function Detail() {
  const navigate = useNavigate()
  const { id } = useParams<{ id: string }>()
  const { setFromNavigation } = battleRecordsStore()

  const [data, setData] = useState<AnalysisResult>()
  const [loading, setLoading] = useState<boolean>(true)

  // 处理返回按钮点击
  const handleGoBack = () => {
    // 设置导航标志，表示是从详情页返回
    setFromNavigation(true)
    navigate('..', { relative: 'path' })
  }

  useEffect(() => {
    if (id) {
      setLoading(true)
      loadSunData(id).then((data) => {
        if (!data) return
        setData(data)
        setLoading(false)
      })
    }
  }, [id])

  // 直接返回 author
  const isSunRoute2 = () => {
    const path = window.location.pathname
    return path.startsWith('/sun') || path.startsWith('/hshe')
  }
  const isSunRoute = () => {
    return true
  }
  // 判断是否拥有 top30_battle_damage 且 top30_battle_receive 且数据不能少于10条
  const showAi = () => {
    return (
      data?.top30_battle_damage &&
      data?.top30_battle_damage.length > 10 &&
      data?.top30_battle_receive &&
      data?.top30_battle_receive.length > 10
    )
  }

  const titlename = () => {
    if (id && id.includes('+')) {
      return '聚合统计'
    } else {
      // 如果是 sun 路由，返回 author
      if (isSunRoute2()) {
        return data?.sumary.author ?? '-战斗数据'
      }
      return '战斗数据'
    }
  }
  const handleRecalculate = async (fast: boolean) => {
    if (id) {
      setLoading(true)
      loadSunData(id, true, fast).then((data) => {
        setLoading(false)
        if (!data) return
        setData(data)
      })
    }
  }
  const columns = [
    { key: 'name', label: '玩家' },
    { key: 'role', label: '职业' },
    { key: 'damage', label: '造成玩家伤害' },
    { key: 'receive', label: '受到玩家伤害' }
    // 敌友
    // { key: 'enemy', label: '敌友' }
  ]

  const show_buffs = ['治愈之风', '神圣洗礼', '净化术']
  // group by role 返回 数组 role, count status 1 敌军， 2 友军  其它 全部
  const transform2Role = (status: number) => {
    // 返回包含三个属性的对象数组：name, value, length
    // 敌军 value=累计伤害，其它/友军 value=length（人数），以便饼图显示正确
    if (!data?.whole_user) return []
    const roleMap = new Map<string, NameValueLength>()
    data?.whole_user.forEach((v) => {
      // 敌军
      if (status === 1 && !v.enemy) return
      // 友军
      if (status === 2 && v.enemy) return
      const roleName = v.role || '未知'
      const count = roleMap.get(roleName) ?? {
        name: roleName,
        value: 0,
        length: 0
      }
      const newLength = count.length + 1
      roleMap.set(roleName, {
        name: roleName,
        value:
          status === 1
            ? count.value + (v.receive || 0) // 敌军累计伤害
            : newLength, // 其它/友军 value=人数
        length: newLength // 都累计人数
      })
    })
    // 返回 NameValueLength[] 根据length排序倒序
    return Array.from(roleMap.values()).sort((a, b) => b.length - a.length)
  }

  const transform2Damage = (): NameValueLength[] => {
    if (!data?.whole_user) return []
    return data.whole_user
      .filter((v) => v.enemy && v.damage > 0)
      .map((v) => {
        return { name: v.name, value: v.damage, length: 0 }
      })
      .sort((a, b) => b.value - a.value)
  }
  const transform2Receive = (): NameValueLength[] => {
    if (!data?.whole_user) return []
    return data.whole_user
      .filter((v) => v.enemy && v.receive > 0)
      .map((v) => {
        return { name: v.name, value: v.receive, length: 0 }
      })
      .sort((a, b) => b.value - a.value)
  }
  const transformWithAgg = (data: BattleValueExt2[]): NameValueLength[] => {
    const groupedData = data.reduce(
      (acc, v) => {
        if (!acc[v.name]) {
          acc[v.name] = { name: v.name, value: 0, length: 0 }
        }
        acc[v.name].value += v.damage
        return acc
      },
      {} as Record<string, NameValueLength>
    )

    return groupedData
      ? Object.values(groupedData).sort((a, b) => b.value - a.value)
      : []
  }
  const cache = new Map()
  const transform2BuffAgg = (
    data: BattleValue[],
    receive: boolean
  ): NameValueLength[] => {
    if (!data) return []
    // 使用缓存避免重复计算
    const cacheKey = receive ? 'receive' : 'damage'
    if (cache.has(cacheKey)) {
      return cache.get(cacheKey)
    }
    // 根据 receive 过滤
    const filteredData = data.filter((v) =>
      receive ? v.action === 'Receive' : v.action === 'Damage'
    )
    // 根据 target 分组
    const groupedData = filteredData.reduce(
      (acc, v) => {
        if (!acc[v.target]) {
          acc[v.target] = { name: v.target, value: 0, length: 0 }
        }
        acc[v.target].value += 1
        acc[v.target].length += 1
        return acc
      },
      {} as Record<string, NameValueLength>
    )
    // 返回 NameValueLength[] 根据value排序倒序
    const result = Object.values(groupedData).sort((a, b) => b.value - a.value)
    cache.set(cacheKey, result)
    return result
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const time_line_buffer = (
    data: BattleValue[],
    receive: boolean
  ): BattleValueExt2[] => {
    console.log('receive', receive)
    if (!data) return []
    // 根据 receive 过滤
    // const filteredData = data.filter((v) =>
    //   receive ? v.action === 'Receive' : v.action === 'Damage'
    // )
    // 先映射
    const mapped = data.map((v) => {
      return {
        name: v.time,
        role: v.target,
        enemy: false, // 默认 false
        damage: v.action === 'Damage' ? 1 : 0,
        receive: v.action === 'Receive' ? 1 : 0,
        count: 1
      }
    })
    // 按 name 累加
    const merged = mapped.reduce(
      (acc, cur) => {
        const key = cur.name
        if (!acc[key]) {
          acc[key] = { ...cur }
        } else {
          acc[key].damage += cur.damage
          acc[key].receive += cur.receive
          acc[key].count += cur.count
        }
        return acc
      },
      {} as Record<string, BattleValueExt2>
    )
    return Object.values(merged)
  }

  const timeline_data = (
    data: BattleValueExt2[],
    start: string,
    end: string
  ) => {
    const convertTo24Hour = (time: string) => {
      const [hours, minutes] = time.split(':').map(Number)
      return hours + minutes / 60
    }

    const start24 = convertTo24Hour(start)
    let end24 = convertTo24Hour(end)
    if (end24 < start24) {
      end24 += 24 * 60
    }

    return data.sort((a, b) => {
      let aTime = convertTo24Hour(a.name)
      let bTime = convertTo24Hour(b.name)

      if (aTime < start24) aTime += 24
      if (bTime < start24) bTime += 24

      return aTime - bTime
    })
  }

  return (
    <main
      className={
        loading
          ? 'h-screen overflow-hidden'
          : 'flex min-h-screen flex-col items-center justify-center bg-gray-50 p-4 sm:p-10'
      }
    >
      {loading ? (
        <DynamicDots
          title="正在分析战斗数据"
          subtitle="正在深度解析您的战斗记录，生成详细的数据报告"
          showProgress={true}
          fullscreen={true}
        />
      ) : (
        <>
          {/* 页面标题和操作区 */}
          <Card className="mb-2 w-full max-w-4xl rounded-xl border border-gray-200 bg-white/90 shadow-lg">
            <CardHeader className="px-2 pb-0.5 pt-2">
              <CardTitle className="text-xl font-bold tracking-tight text-gray-900">
                {titlename()}
              </CardTitle>
              {data?.sumary.time && (
                <CardDescription className="mt-0.5 text-xs text-gray-400">
                  分析时间: {data?.sumary.time}
                </CardDescription>
              )}
            </CardHeader>
            <CardContent className="px-2 pb-1 pt-0.5">
              <div className="mb-1 flex flex-col gap-1 sm:flex-row sm:items-center">
                <div className="flex flex-wrap gap-1">
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 rounded border-none px-1 text-[10px] text-gray-800 shadow-none hover:text-gray-900"
                    onClick={handleGoBack}
                  >
                    返回
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 rounded border-none px-1 text-[10px] text-gray-400 shadow-none hover:text-gray-500"
                    onClick={() => handleRecalculate(true)}
                  >
                    分析所有目标
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 rounded border-none px-1 text-[10px] text-gray-400 shadow-none hover:text-gray-500"
                    onClick={() => handleRecalculate(false)}
                  >
                    排除未知(怪)目标
                  </Button>
                </div>

                {/* AI分析按钮 */}
                {showAi() && <AnalysisComponent />}
              </div>
            </CardContent>
          </Card>

          {/* 统计数据区块 */}
          <Card className="mb-6 w-full max-w-4xl rounded-lg">
            <CardContent className="p-0">
              {data && <SummaryStats data={data} isSunRoute={isSunRoute} />}
            </CardContent>
          </Card>
          {((data?.top30_battle_damage &&
            data?.top30_battle_damage.length > 0) ||
            (data?.top30_battle_receive &&
              data?.top30_battle_receive.length > 0)) && (
            <Top30Table
              out={data?.top30_battle_damage}
              received={data?.top30_battle_receive}
            />
          )}
          {/* radar */}
          {data?.radar_data && <Radar data={data.radar_data} />}
          {/* time line */}
          {data?.time_line && data?.time_line.length > 0 && (
            <div className="mb-2 w-full max-w-4xl shadow-md">
              <SmoothData
                title="输出承受伤害"
                tag="伤害次数"
                damage="输出伤害"
                receive="承受伤害"
                data={timeline_data(
                  data?.time_line,
                  data?.sumary.time_range_start,
                  data?.sumary.time_range_end
                )}
              />
            </div>
          )}
          {/* time 击杀 被杀 */}
          {data?.time_killer && data?.time_killer.length > 0 && (
            <div className="mb-4 w-full max-w-4xl shadow-md">
              <SmoothData
                title="击杀/被杀"
                // 根据name顺序排序
                data={timeline_data(
                  data?.time_killer,
                  data?.sumary.time_range_start,
                  data?.sumary.time_range_end
                )}
                receive="被杀"
                damage="击杀"
                tag=""
              />
            </div>
          )}
          {/* 承受洗礼详情 buffer_data 过滤Receive的数据，且根据 target分组 */}
          {data?.buffer_data &&
            data?.buffer_data.length > 0 &&
            transform2BuffAgg(data?.buffer_data, true).length > 0 && (
              <div className="mb-2 w-full max-w-4xl shadow-md" id="buffer_data">
                <Pie
                  title="享受洗礼"
                  tag="提供洗礼"
                  unit="次"
                  sum={true}
                  data={transform2BuffAgg(data?.buffer_data, true)}
                />
              </div>
            )}
          {/* 洗礼承受时间轴 */}
          {data?.buffer_data &&
            data?.buffer_data.length > 0 &&
            time_line_buffer(data?.buffer_data, true).length > 0 && (
              <div className="mb-4 w-full max-w-4xl shadow-md">
                <SmoothData
                  damage="输出洗礼"
                  receive="承受洗礼"
                  tag="总次数"
                  title="洗礼承受趋势"
                  data={time_line_buffer(data?.buffer_data, true)}
                />
              </div>
            )}
          {/* 输出洗礼 */}
          {data?.buffer_data &&
            data?.buffer_data.length > 0 &&
            transform2BuffAgg(data?.buffer_data, false).length > 0 && (
              <div className="mb-4 w-full max-w-4xl shadow-md" id="output_buff">
                <Pie
                  title="输出洗礼"
                  tag="输出洗礼"
                  unit="次"
                  sum={true}
                  data={transform2BuffAgg(data?.buffer_data, false)}
                />
              </div>
            )}
          {/* 技能 忽略掉追加效果 */}
          {data?.skills_buff &&
            data?.skills_buff
              .map((v) => v.name)
              .filter((v) => show_buffs.includes(v)).length > 0 && (
              <div className="mb-4 w-full max-w-4xl shadow-md">
                <Pie
                  title="增益buff"
                  tag="次数"
                  data={data?.skills_buff
                    .filter((v) => show_buffs.includes(v.name))
                    .map((v) => {
                      return { name: v.name, value: v.count, length: 0 }
                    })
                    .sort((a, b) => b.value - a.value)}
                />
              </div>
            )}
          {/* 转成pie */}
          {data?.whole_user &&
            data?.whole_user.filter((v) => v.enemy && v.damage > 0).length >
              0 && (
              <div
                className="mb-4 w-full max-w-4xl shadow-md"
                id="output_damage"
              >
                <Pie
                  title="输出伤害"
                  tag="造成玩家伤害"
                  data={transform2Damage()}
                  // sum={true}
                />
              </div>
            )}
          {/* 转成pie */}
          {data?.whole_user &&
            data?.whole_user.filter((v) => v.enemy && v.receive > 0).length >
              0 && (
              <div
                className="mb-4 w-full max-w-4xl pt-5 shadow-md"
                id="receive_damage"
              >
                <Pie
                  title="承受伤害"
                  tag="承受玩家伤害"
                  data={transform2Receive()}
                  // sum={true}
                />
              </div>
            )}
          {/* 技能榜 */}
          {data?.skills_damage && data?.skills_damage.length > 0 && (
            <div className="mb-4 w-full max-w-4xl shadow-md">
              <Pie
                title="输出技能伤害"
                tag="技能输出伤害"
                data={data?.skills_damage
                  .map((v) => {
                    return { name: v.name, value: v.damage, length: 0 }
                  })
                  .sort((a, b) => b.value - a.value)}
                // sum={true}
              />
            </div>
          )}
          {data?.skills_receive && data?.skills_receive.length > 0 && (
            <div className="mb-4 w-full max-w-4xl shadow-md">
              <Pie
                title="承受技能伤害"
                tag="承受技能伤害"
                data={data?.skills_receive
                  .map((v) => {
                    return { name: v.name, value: v.receive, length: 0 }
                  })
                  .sort((a, b) => b.value - a.value)}
                // sum={true}
              />
            </div>
          )}
          {data?.kill_death &&
            data?.kill_death.filter((v) => v.damage > 0).length > 0 && (
              <div className="mb-4 w-full max-w-4xl shadow-md">
                <Pie
                  title="击杀玩家"
                  title2="人头"
                  tag="击杀"
                  data={transformWithAgg(
                    data?.kill_death.filter((v) => v.damage > 0)
                  )}
                />
              </div>
            )}
          {/* 被杀 */}
          {data?.kill_death &&
            data?.kill_death.filter((v) => v.receive > 0).length > 0 && (
              <div className="mb-4 w-full max-w-4xl shadow-md" id="death_count">
                <Pie
                  title="死亡次数"
                  tag="死亡次数"
                  data={transformWithAgg(
                    data?.kill_death.filter((v) => v.receive > 0)
                  )}
                />
              </div>
            )}
          {/* 所有其它buff */}
          {data?.skills_buff &&
            data?.skills_buff
              .map((v) => v.name)
              .filter((v) => !show_buffs.includes(v) && v != '追加效果')
              .length > 0 && (
              <div className="mb-4 w-full max-w-4xl shadow-md">
                <Pie
                  title="其它状态buff"
                  tag="次数"
                  data={data?.skills_buff
                    .filter(
                      (v) =>
                        !show_buffs.includes(v.name) && v.name != '追加效果'
                    )
                    .map((v) => {
                      return { name: v.name, value: v.count, length: 0 }
                    })
                    .sort((a, b) => b.value - a.value)}
                />
              </div>
            )}
          {/* 职业汇总 */}
          {isSunRoute() &&
            data?.whole_user &&
            data?.whole_user.filter((v) => v.enemy).length > 0 && (
              <div className="mb-10 w-full max-w-4xl shadow-md">
                {/* 数据转成 [name, len, value] */}
                <Pie
                  title="敌军职业分布"
                  title2="敌军职业伤害"
                  tag="承受该职业总伤害"
                  data={transform2Role(1)}
                  // sum={true}
                  count={true}
                />
              </div>
            )}

          {/* 职业汇总 */}
          {isSunRoute() && data?.whole_user && data?.whole_user.length > 0 && (
            <div className="mb-6 w-full max-w-4xl shadow-md">
              {/* 数据转成 [name, len, value] */}
              <Pie
                title="全员职业分布"
                // title2="敌军职业伤害"
                // tag="承受敌军伤害"
                data={transform2Role(3)}
                count={true}
                tag="人数"
              />
            </div>
          )}

          {isSunRoute() &&
            data?.whole_user &&
            data?.whole_user.filter((v) => !v.enemy).length > 0 && (
              <div className="mb-10 w-full max-w-4xl shadow-md">
                {/* 数据转成 [name, len, value] */}
                <Pie
                  title="友军职业分布"
                  // tag="承受敌军伤害"
                  data={transform2Role(2)}
                  count={true}
                  sum={false}
                  tag="人数"
                />
              </div>
            )}
          {isSunRoute() && data?.whole_user && data?.whole_user.length > 0 && (
            <div className="mb-2 w-full max-w-4xl rounded-lg bg-white p-2 shadow-md">
              {data?.whole_user.filter((v) => !v.enemy).length > 0 && (
                <div className="flex flex-col" id="enemy_role">
                  <SortableTable
                    title={`敌军人员 (${
                      data?.whole_user.filter((v) => v.enemy).length
                    }人)`}
                    data={data?.whole_user.filter((v) => v.enemy)}
                    columns={columns}
                  />
                </div>
              )}
              {/* dash line */}
              {data?.whole_user.filter((v) => !v.enemy).length > 0 && (
                <>
                  <div className="mt-4 border-t pt-4" />
                  <div className="overflow-x-auto">
                    <SortableTable
                      enemy={false}
                      title={`友军人员 (${
                        data?.whole_user.filter((v) => !v.enemy).length
                      }人)`}
                      data={data?.whole_user.filter((v) => !v.enemy)}
                      columns={columns}
                    />
                  </div>
                </>
              )}
            </div>
          )}
          <Toaster />
        </>
      )}
    </main>
  )
}
